<template>
    <div id="app" style="display: flex;flex-flow:column"
         :style="{'justify-content': loginFromVisible ? 'center':'', 'align-items': loginFromVisible ? 'center':''}">
        <!--        <el-radio-group v-model="value1"  >-->
        <!--            <el-radio v-for="item in data2" :label="item['valueField']"-->
        <!--                      :key="item['valueField']">{{item['labelField']}}-->
        <!--            </el-radio>-->
        <!--        </el-radio-group>-->
        <div v-if="loginFromVisible && w">
            <div style="background-color: aliceblue;padding:30px;">
                <a class="link" href="https://www.google.cn/chrome/" target="_blank">为了更新的浏览效果,请使用最新版Chrome浏览器。</a>
                或是
                <a class="link" @click="w=false">继续</a>
            </div>
        </div>
        <template v-else>
            <image-edit></image-edit>
            <vHead ref="head" v-if="loginFromVisible === false"></vHead>

<!--            <div style="display: flex;flex-flow:row;flex:1;" v-if="loginFromVisible === false">-->
<!--                <vSidebar ref="menu" :index="menu_index" :menus="menus"></vSidebar>-->
<!--                <div class="content" v-loading="loading === true" element-loading-text="拼命加载中"-->
<!--                     id="app-content">-->
<!--                    -->
<!--                </div>-->
<!--            </div>-->
            <transition name="move" mode="out-in" v-if="loginFromVisible === false">
                <router-view :key="url"></router-view>
            </transition>

            <div v-if="loginFromVisible">
                <h1 style="top: 100px;margin-left:-200px;position:fixed;font-size: 24px;font-weight: normal;color: darkblue;">
                    站点管理</h1>

                <div :style="{'background-image': 'url(' +bg+')'}"
                     style="background-repeat: no-repeat;background-size: 100% 100%;padding:20px 160px 20px 20px">
                    <div style="width:360px;">
                        <kv label="用户名">
                            <el-input v-model.trim="loginInfo.loginName" placeholder="请输入用户名" chk="*"></el-input>
                        </kv>
                        <kv label="密码">
                            <el-input type="password" v-model.trim="loginInfo.password" placeholder="请输入密码"
                                      chk="*"></el-input>
                        </kv>
                        <kv label="验证码" v-if="needValidateCode">
                            <div style="display: flex">
                                <el-input v-model.trim="loginInfo.validateCode" placeholder="请输入验证码"
                                          @keyup.enter.native="login()" chk="*"></el-input>
                                <img class="validate-img" id="validateCodeImage" style="width:200px;margin-left:5px;"
                                     :src="loginInfo.validateImg"
                                     @click="img_click"/></div>
                        </kv>
                        <div class="login-btn">
                            <el-button type="primary" @click="login()" style="padding:6px 24px;">登录</el-button>
                        </div>
                    </div>
                </div>
            </div>

        </template>
        <div style="position:fixed;bottom:100px;" v-if="loginFromVisible">
            版权所有：dev8.cn
        </div>
    </div>
</template>

<script>
    import header from './view/common/Header.vue'
    import sidebar from './view/common/Sidebar.vue'
    import bg_1 from "./view/assets/login_input.png"


    export default {
        data() {
            return {
                // value1: true,
                // data2:[
                //     {"keyField":"true","valueField":"abc"},
                //     {"keyField":"false","valueField":"def"},
                //     {"keyField":"","valueField":"nul"}],
                bg: bg_1,
                w: true,
                menu_index: 0,
                loading: false,
                user: {name: ""},
                menus: [],    //菜单
                corp: {logo: {url: ""}, name: ""},
                needValidateCode: true,
                permission: [],
                popData: {tags: [], allProducts: [], products: []},  //弹出数据
                cartNumber: 0, //购物车数量

                authPermission: false,
                authPermissionErrorMsg: "",
                //登录使用的用户名密码。
                loginInfo: {
                    loginName: '',
                    password: '',
                    validateImg: '',
                },
                rules: {
                    loginName: [
                        {required: true, message: '请输入用户名', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'}
                    ],
                    validateCode: [
                        {required: true, message: '请输入验证码', trigger: 'blur'}
                    ]
                },
                loginFromVisible: null,
            };
        },
        components: {
            vHead: header,
            vSidebar: sidebar
        },
        created() {
            jv.main = this;

            var isFirefox = navigator.userAgent.indexOf('Firefox') > -1  // 是否是火狐  ，火狐内核Gecko
            console.log('火狐' + isFirefox)  // 返回 true  则是 ，false  则不是

            var isWebKit = navigator.userAgent.indexOf('WebKit') > -1  // 是否是WebKit 内核
            console.log('谷歌内核' + isWebKit)  // 返回 true  则是，false  则不是

            var isChrome = navigator.userAgent.indexOf('Chrome') > -1  // 是否是谷歌
            console.log('谷歌' + isChrome)  // 返回 true  则是 ，false  则不是

            var isAppleWebKit = navigator.userAgent.indexOf('AppleWebKit') > -1  // 是否是谷歌
            console.log('谷歌' + isChrome)  // 返回 true  则是 ，false  则不是

            if (isFirefox || isWebKit || isChrome || isAppleWebKit) {
                this.w = false;
            } else {
                this.w = true;
            }

            Object.defineProperty(this, "download_url", {
                set(url) {
                    console.log(url);
                    if (!url) return;
                    jv.downloadFile(url);
                }
            });
        },

        mounted() {
            this.user = jv.store.getJson("main") || {};

            this.loginInfo.loginName = window.localStorage.getItem('admin-userName');
            this.img_click();

            // this.$nextTick(it => {
            //     if (document.body.clientWidth < 800) {
            //         document.body.style.height = "auto";
            //         document.querySelector("#app>div>.sidebar").parentNode.style.flexFlow = "column";
            //     }
            // })
            // this.$http.post("/site/config/get").then(res => {
            //     this.needValidateCode = res.data.data.needValidateCode;
            // });

            this.loadData();
        },
        methods: {
            open_download_url(url) {
                if (!url) return;
                var div = document.getElementById("download_div");
                div.innerHTML = "";
                div.innerHTML = "<iframe url=\"" + url + "\"/>";
            },
            menu(index) {
                this.menu_index = index;
            },
            //登陆
            login() {
                // this.$refs['loginInfo'].validate((valid) => {
                //     if (valid) {
                //
                //     } else {
                //         return false
                //     }
                // })

                if (jv.main.chk() == false) {
                    return;
                }

                this.$http.post("/open/login", this.loginInfo).then(res => {
                    window.localStorage.setItem('admin-userName', this.loginInfo.loginName);

                    var json = res.data.data;
                    this.setJson(json);
                    // jv.store.setJson("plan", json.defaultPlan);
                    this.loginFromVisible = false;
                    if (this.authUrl() === false) {
                        return;
                    }

                    this.setMenu();
                }, res => {
                    this.img_click();
                });
            },
            img_click() {
                // if (jv.token) {
                //     this.loginInfo.validateImg = window.Server_Host + "/open/validate-code-image?_=" + jv.random() + "&token=" + jv.token;
                //     return;
                // }
                this.$http.get("/open/token?_=" + jv.random()).then(res => {
                    jv.token = res.data.data;
                    this.loginInfo.validateImg = window.Server_Host + "/open/validate-code-image?_=" + jv.random() + "&token=" + jv.token;
                });
            },
            toHome() {
                window.location.href = "../"
            },
            //重置
            // reset_password() {
            //     jv.prompt("请输入登录名").then(res => {
            //         this.$http.post("/user/forgetPassword", {loginName: res.value})
            //             .then(function (data) {
            //                 jv.info("重置密码申请已成功发送，请联系管理员。");
            //             })
            //     })
            // },
            setJson(json) {
                window.Upload_Host = json.uploadHost;
                this.user = json;
                jv.store.setJson("main", json);

                Object.assign(this, json);
            },
            authUrl(url) {
                this.authPermission = true;

                let hash = window.location.hash;
                if (!hash) {
                    return;
                }

                url = url || hash.substring(1);

                if (url == "/") return;
                if (url == "/error") return;
                if (url == "/noPermissoin") return;
                if (url == "/basicInfo" && this.user.admin) return;
                if (url == "/info/corp" && this.user.admin) return;

                if (jv.main.corp.locked) {
                    this.authPermissionErrorMsg = jv.main.corp.lockedRemark || "该企业被禁止访问";
                    this.authPermission = false;
                    return false;
                }

                if (jv.main.$router.options.permission &&
                    (jv.main.$router.options.permission.indexOf(url) >= 0) &&
                    ((jv.main.permission || []).indexOf(url) < 0)) {
                    console.warn("没有权限:" + url)
                    this.authPermissionErrorMsg = "没有权限";
                    this.authPermission = false;
                    return false;
                }

                return;
            },

            add2AllProduct(product) {
                if (!product || !product.id) return;
                if (this.popData.allProducts.last(it => it.id == product.id)) return;
                this.popData.allProducts.push(product);
            },
            addTag(tagInfo) {
                if (!tagInfo || !tagInfo.tags || !tagInfo.tags.length) return;
                var item = this.popData.tags.last(it => it.action == tagInfo.action)

                if (!item) {
                    this.popData.tags.push({action: tagInfo.action, tags: tagInfo.tags});
                    return;
                }

                var leftTags = tagInfo.tags.filter(it => item.tags.indexOf(it));
                if (leftTags.length) {
                    Array.prototype.push.apply(item.tags, leftTags);
                }
            },
            addUser(user) {
                if (!user || !user.id) return;
                if (this.popData.handlers.last(it => it.id == user.id)) return;
                this.popData.handlers.push(user);
            },
            loadData() {
                this.$http.post("/loginInfo/getMine").then(res => {
                    var json = res.data.data;


                    this.setJson(json);

                    this.loginFromVisible = false;


                    if (this.authUrl() === false) {
                        return;
                    }

                    this.setMenu();
                });
            },
            setMenu() {
                var menus = [

                ];
                if (this.user.isAdmin) {
                    menus.push({
                        "id": "3",
                        "code": "s3",
                        "name": "用户管理",
                        "url": "/admin-user/list",
                        "css": "set-corp",
                        "pages": {},
                        "subMenus": []
                    })
                }

                this.menus = menus;
            }
        },
        watch: {
            loginFromVisible(value) {
                if (value) {
                    this.$nextTick(() => {
                        document.body.classList.add("bg2");
                    });

                    this.img_click();
                } else {
                    this.$nextTick(() => {
                        document.body.classList.remove("bg2");
                    })
                }
            },
        },
        computed: {
            url() {
                return this.$route.path
            }
        }
    }

</script>


<style lang="scss" scoped>
    /deep/ .k {
        min-width: 64px;
    }


    .centerDialog {
        .el-dialog {
            max-width: 400px;
        }
    }

    .content {
        padding: 20px;
        box-sizing: border-box;
        overflow-y: scroll;
        background-color: #fff;
        /*background-color: rgb(245,245,251);*/
        flex: 1;
        display:flex;
    }

    .move-enter-active, .move-leave-active {
        transition: opacity 1.1s;
    }

    .move-enter, .move-leave {
        opacity: 0;
    }

    .login-btn {
        margin-top: 10px;
        text-align: center;
    }

    .el-date-editor--daterange.el-input {
        width: 230px;
    }

    .el-tabs__header {
        margin: 0;
    }

    .img_text {
        textarea {
            margin-top: 4px;
            max-height: 200px;
        }
    }
</style>

